﻿#include "DialogSubscriber.h"
#include "ui_DialogSubscriber.h"

DialogSubscriber::DialogSubscriber(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogSubscriber)
{
    ui->setupUi(this);
}

DialogSubscriber::~DialogSubscriber()
{
    if(_subscriber!=nullptr)
    {
        disconnect(_subscriber,&BaseSubscriber::Receive,this,&DialogSubscriber::OnDataReceive);
    }
    delete ui;
}

void DialogSubscriber::SetCommunication(BaseSubscriber *subscriber)
{
    _subscriber=subscriber;
    connect(_subscriber,&BaseSubscriber::Receive,this,&DialogSubscriber::OnDataReceive,Qt::DirectConnection);
    ui->txtMsg->clear();
}

void DialogSubscriber::on_btnPublish_clicked()
{
    QString text=ui->lineEdit->text();
    _subscriber->Publish(text.toUtf8());
}

void DialogSubscriber::OnDataReceive(QByteArray data)
{
//    qDebug()<<data;
    AddNewLine(QString::fromUtf8(data));
}

void DialogSubscriber::AddNewLine(QString line)
{
    if(!this->isHidden())
    {
        QTextCursor cursor = ui->txtMsg->textCursor();
        // 移动光标到文本末尾
        cursor.movePosition(QTextCursor::End);
        // 插入新的一行文本
        cursor.insertBlock();
        cursor.insertText(line);
        // 设置光标到新的一行
        ui->txtMsg->setTextCursor(cursor);
    }
}
